package org.etom.impl.ui;

import java.io.IOException;

import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.etom.connector.service.MoodleConnector;
import org.etom.impl.ui.util.CommonMessages;
import org.etom.impl.ui.util.ConnectionStorage;
import org.etom.impl.ui.util.Logger;
import org.etom.impl.ui.util.ResourceManager;
import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;

/**
 * The activator class controls the plug-in life cycle
 */
public class Activator extends AbstractUIPlugin {

  // The plug-in ID
  public static final String PLUGIN_ID = "EtoM_UI"; //$NON-NLS-1$

  // The shared instance
  private static Activator plugin;

  private ServiceTracker connectorTracker;
  private ConnectionStorage connectionStorage;
  private ResourceManager resourceManager;
  private BundleContext bc;
  
  /**
   * The constructor
   */
  public Activator() {
  }

  /*
   * (non-Javadoc)
   * 
   * @see
   * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
   * )
   */
  public void start(BundleContext context) throws Exception {
    this.bc = context;
    super.start(context);
    plugin = this;
  }

  /*
   * (non-Javadoc)
   * 
   * @see
   * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
   * )
   */
  public void stop(BundleContext context) throws Exception {
    plugin = null;
    super.stop(context);
    if (connectorTracker != null) {
      connectorTracker.close();
      connectorTracker = null;
    }
    this.connectionStorage = null;
    this.bc = null;
  }

  /**
   * The method returns the moodle connector service.
   * 
   * @return the moodle connector service if available
   *         and <code>null</code> if not
   */
  public MoodleConnector getMoodleConnector() {
    if (connectorTracker == null) {
      connectorTracker = new ServiceTracker(bc, MoodleConnector.class.getName(), null);
      connectorTracker.open();
    }
    return (MoodleConnector) connectorTracker.getService();
  }
  
  /**
   * The method returns connection storage.
   * 
   * @return the connection storage
   */
  public ConnectionStorage getConnectionStorage() {
    if (connectionStorage == null) {
      connectionStorage = new ConnectionStorage(bc);
    }
    return connectionStorage;
  }
  
  /**
   * The method cares about the resource manager.
   * 
   * @return the resource manager
   */
  public ResourceManager getResourceManager() {
    if (null == resourceManager) {
      try {
        resourceManager = new ResourceManager(bc);
      } catch (IOException ioe) {
        resourceManager = null;
        Logger.ERROR(CommonMessages.Res_Manager_Init_Fail, ioe);
      }
    }
    return resourceManager;
  }
  
  /**
   * Returns the shared instance
   * 
   * @return the shared instance
   */
  public static Activator getDefault() {
    return plugin;
  }

}
